/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.contract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.mysql.dto.ExportExcelDTO;
import com.pig4cloud.pigx.common.customize.mysql.utils.ExportExcelUtils;
import com.pig4cloud.pigx.contract.dto.ContractHistoryTradeDTO;
import com.pig4cloud.pigx.contract.entity.ContractSymbol;
import com.pig4cloud.pigx.contract.entity.ContractTrade;
import com.pig4cloud.pigx.contract.enums.ContractOrderEnum;
import com.pig4cloud.pigx.contract.mapper.ContractSymbolMapper;
import com.pig4cloud.pigx.contract.mapper.ContractTradeMapper;
import com.pig4cloud.pigx.contract.service.ContractTradeService;
import com.pig4cloud.pigx.contract.utils.ContractUtils;
import com.pig4cloud.pigx.contract.vo.ContractHistoryTradeVO;
import com.pig4cloud.pigx.contract.vo.ContractStatisticsHandlingFeeVO;
import lombok.AllArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 成交记录表
 *
 * @date 2022-08-11 10:08:52
 */
@Service
@AllArgsConstructor
public class ContractTradeServiceImpl extends ServiceImpl<ContractTradeMapper, ContractTrade> implements ContractTradeService {

    private final ContractUtils contractUtils;
    private final ContractSymbolMapper symbolMapper;

    private final ExportExcelUtils excelUtils;

    @Override
    public R getHistoryTrade(Page page, ContractHistoryTradeDTO dto) {
        IPage<ContractHistoryTradeVO> trade = baseMapper.getHistoryTrade(page,
                dto.getUserId(),
                dto.getStartTime(),
                dto.getEndTime(),
                dto.getSymbolId()
        );
        // 编码翻译
        trade.getRecords().forEach(e -> {
            e.setSideCn(ContractOrderEnum.Side.findName(e.getSide().toString()));
            e.setOrderTypeCn(ContractOrderEnum.Type.findName(e.getOrderType().toString()));
            e.setCurrencyNum(e.getNum().multiply(e.getPrice()));
            e.setOperationType(ContractOrderEnum.OperationType.findName(e.getOperationType()));
            // 设置精度
            contractUtils.setScaleBySymbol(e, e.getSymbolName());
            // 查询币对详情
            ContractSymbol symbol = symbolMapper.selectOne(new QueryWrapper<ContractSymbol>() {{
                eq("name", e.getSymbolName());
                select("main_cur_name,token_cur_name,sheet");
            }});
            // 主币外币名称
            e.setMainCurName(symbol.getMainCurName());
            e.setTokenCurName(symbol.getTokenCurName());
            e.setSheet(symbol.getSheet());
        });

        // 清空localThread币对缓存
        ContractUtils.removeSymbolThreadCache();
        return R.ok(trade);
    }

    @Override
    public List<ContractStatisticsHandlingFeeVO> statisticsHandlingFee(LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.statisticsHandlingFee(startTime, endTime);
    }

    @Override
    public HSSFWorkbook excel(LocalDateTime startTime, LocalDateTime endTime) {
        // 初始化excel参数
        ExportExcelDTO dto = new ExportExcelDTO();
        // 自定义表头长度
        List<Short> columnWidth = new ArrayList<Short>() {{
            add((short) 130);
            add((short) 180);
            add((short) 200);
            add((short) 300);
            add((short) 300);
        }};
        dto.setColumnWidth(columnWidth);
        // 自定义表头名称
        List<String> columnLabel = new ArrayList<String>() {{
            add("币对名称");
            add("订单类型");
            add("成交次数");
            add("手续费总额(USDT)");
            add("平均手续费率(%)");
        }};
        dto.setColumnLabel(columnLabel);
        dto.setHeaderTitle("手续费统计报表");
        dto.setHeaderTime("--");
        HSSFWorkbook wb = new HSSFWorkbook();
        // 默认sheet1
        HSSFSheet sheet = wb.createSheet("sheet1");
        // 统一格式初始化
        excelUtils.init(dto, wb, sheet);
        // 单元格
        HSSFCell cell;
        // 初始化数据单元格的样式
        HSSFCellStyle labelStyle = ExportExcelUtils.getCellStyle(wb, null, (short) 11, false);
        // 基础数据起始行
        int startRow = 3;
        // 查询需要导出的数据
        List<ContractStatisticsHandlingFeeVO> list = baseMapper.statisticsHandlingFee(startTime, endTime);
        // 循环将数据写入单元格
        // 手续费合计
        BigDecimal handlingFeeTotal = BigDecimal.ZERO;
        long countTotal = 0;
        for (int i = 0; i < list.size(); i++) {
            // 行数
            int createRow = startRow + i;
            // 创建行
            HSSFRow label = sheet.createRow(createRow);
            // 币对名称
            cell = label.createCell(0);
            cell.setCellValue(list.get(i).getSymbolName());
            cell.setCellStyle(labelStyle);
            // 订单类型
            cell = label.createCell(1);
            cell.setCellValue(ContractOrderEnum.Type.findName(list.get(i).getOrderType()));
            cell.setCellStyle(labelStyle);
            // 成交次数
            cell = label.createCell(2);
            cell.setCellValue(list.get(i).getCount());
            cell.setCellStyle(labelStyle);
            countTotal += list.get(i).getCount();
            // 手续费总额
            cell = label.createCell(3);
            cell.setCellValue(list.get(i).getHandlingFee().stripTrailingZeros().toPlainString());
            cell.setCellStyle(labelStyle);
            handlingFeeTotal = handlingFeeTotal.add(list.get(i).getHandlingFee());
            // 平均手续费率
            cell = label.createCell(4);
            cell.setCellValue(list.get(i).getHandlingFeeRate().stripTrailingZeros().toPlainString());
            cell.setCellStyle(labelStyle);
        }
        // 最后一行做统计
        HSSFCellStyle totalStyle = ExportExcelUtils.getCellStyle(wb, IndexedColors.PALE_BLUE.index, (short) 11, false);
        int totalRow = startRow + list.size();
        HSSFRow label = sheet.createRow(totalRow);

        cell = label.createCell(0);
        cell.setCellValue("合计");
        cell.setCellStyle(totalStyle);

        cell = label.createCell(1);
        cell.setCellValue("/");
        cell.setCellStyle(totalStyle);

        cell = label.createCell(2);
        cell.setCellValue(countTotal);
        cell.setCellStyle(totalStyle);

        cell = label.createCell(3);
        cell.setCellValue(handlingFeeTotal.stripTrailingZeros().toPlainString());
        cell.setCellStyle(totalStyle);

        cell = label.createCell(4);
        cell.setCellValue("/");
        cell.setCellStyle(totalStyle);

        return wb;
    }

}
